package com.tancire.question.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tancire.common.exception.ServiceException;
import com.tancire.common.utils.RsaUtils;
import com.tancire.common.utils.ServletUtils;
import com.tancire.system.domain.SysApp;
import com.tancire.system.domain.SysAppLog;
import com.tancire.system.service.ISysAppLogService;
import com.tancire.system.service.ISysAppService;
import com.tancire.system.service.ISysConfigService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class OpenAuthUtils {

    public static final String AUTH_KEY = "auth";

    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysAppService sysAppService;

    @Resource
    private ISysAppLogService sysAppLogService;


    /**
     * 校验是否开启了开放接口
     *
     * @return
     */
    public boolean checkApiOpen() {
        String msOpenApiStatus = configService.getSysConfigByKey("msOpenApiStatus");
        if ("ON".equalsIgnoreCase(msOpenApiStatus)) {
            return true;
        }
        return false;
    }

    /**
     * 断言开放接口
     */
    public void assertApiOpen() {
        if (!this.checkApiOpen()) {
            throw new ServiceException("当前接口未开放，请联系管理员维护");
        }
        try {
            // 获取请求头信息
            String authData = this.getAuthData();
            // 获取APP信息
            Long appId = this.getAppId();
            SysApp sysApp = sysAppService.selectSysAppByAppId(appId);
            Integer appStatus = sysApp.getAppStatus();
            if (null == appStatus || appStatus != 0) {
                throw new ServiceException("应用被封禁");
            }
            Date appExpirationTime = sysApp.getAppExpirationTime();
            if (null != appExpirationTime && new Date().getTime() > appExpirationTime.getTime()) {
                throw new ServiceException("接口授权已到期，请及时充值");
            }
            String data = RsaUtils.rsaDecrypt(null, sysApp.getPrvKey(), authData);
            JSONObject jsonObject = JSON.parseObject(data);
            String appIdCheck = jsonObject.getString("appId");
            Long curTime = jsonObject.getLong("curTime");
            long time = new Date().getTime();
            if (Math.abs(curTime - time) > (1000 * 60 * 2)) {
                throw new ServiceException("授权超时");
            }
            if (!appIdCheck.equals(appId.toString())) {
                throw new ServiceException("授权校验失败");
            }
        } catch (Exception e) {
            throw new ServiceException("权限校验失败");
        }
    }

    /** 记录访问日志 */
    public void saveRequestLog(String busKey, String remark, String busData) {
        try {
            SysAppLog appLog = new SysAppLog();
            appLog.setAppId(this.getAppId());
            appLog.setBusKey(busKey);
            appLog.setRemark(remark);
            appLog.setBusData(busData);
            this.sysAppLogService.insertSysAppLog(appLog);
        } catch (Exception e) {
            // 异常暂时不处理
            e.printStackTrace();
        }
    }

    /**
     * 从请求头获取appId
     *
     * @return
     */
    private Long getAppId() {
        try {
            return Long.parseLong(ServletUtils.getRequest().getHeader("appid"));
        } catch (Exception e) {
            throw new ServiceException("非法请求");
        }
    }

    /**
     * 获取当前请求头数据
     *
     * @return
     */
    private String getAuthData() {
        try {
            return ServletUtils.getRequest().getHeader(AUTH_KEY);
        } catch (Exception e) {
            throw new ServiceException("非法请求");
        }
    }
}
